/*
 * Copyright (c) 2019. Mikes. All rights reserved.
 *
 * You can contact me with sending email to bWlrZXNfMjAxMkAxNjMuY29t for more information!
 */

package com.climber.android.commonres.app

import com.climber.android.commonres.entity.IncUserInfo
import com.climber.android.commonres.entity.Token
import com.climber.android.commonres.helper.WebCacheHelper
import com.climber.android.commonsdk.app.AppConstants
import com.climber.android.commonsdk.event.BusProvider
import com.climber.android.commonsdk.event.CommonBusEvent
import io.ganguo.library.mvp.Config
import io.ganguo.library.mvp.util.GsonUtils
import io.ganguo.library.mvp.util.StringUtils

/**
 * Created by Mikes at 2019-11-03 22:52
 */
object AppAccount {
    var loginToken: Token? = null
        get() {
            val tokenStr = Config.getString(AppConstants.config_Token)
            return if (StringUtils.isNotEmpty(tokenStr)) {
                GsonUtils.fromJson(tokenStr, Token::class.java)
            } else {
                null
            }
        }
        set(value) {
            field = value
            if (value != null) {
                Config.putString(AppConstants.config_Token, GsonUtils.toJson(value))
            } else {
                Config.remove(AppConstants.config_Token)
            }
        }

    fun clearLoginToken(){
        loginToken = null
    }

    var incUserInfo: IncUserInfo? = null
        get() {
            val userStr = Config.getString(AppConstants.config_loginUser)
            return if (StringUtils.isNotEmpty(userStr)) {
                GsonUtils.fromJson(userStr, IncUserInfo::class.java)
            } else {
                null
            }
        }
        set(value) {
            field = value

            if (value != null) {
                Config.putString(AppConstants.config_loginUser, GsonUtils.toJson(value))
            } else {
                Config.remove(AppConstants.config_loginUser)
            }
        }

    /**
     * 是否已经登录
     * user != null
     *
     * @return
     */
    fun isAuthenticated(): Boolean {
        return incUserInfo != null && loginToken?.token != null
    }

    fun continueIfLogin() : Boolean{
        return if(isAuthenticated()){
            true
        } else{
            BusProvider.getInstance().post(CommonBusEvent.NeedTokenEvent())
            false
        }
    }

    //clear account info when logout.
    fun clear() {
        clearLoginToken()
        incUserInfo = null

        //退出时清楚web缓存, web Cookie
        WebCacheHelper.clearWebStorageAndCookie()
    }
}